package thomasweb.spring.data.controller;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import thomasweb.spring.data.entity.community.CityRepository;
import thomasweb.spring.data.entity.community.OurCity;
import thomasweb.spring.data.entity.statistic.entity.LoginRecords;
import thomasweb.spring.data.entity.statistic.repo.LoginRecordsRepository;

@RestController
public class SampleController {
	
	@Autowired
	private CityRepository cityRepository;
	
	@Autowired
	private LoginRecordsRepository loginRecordsRepository;
	
	private Log LOG = LogFactory.getLog(SampleController.class);
	
    @RequestMapping("/")
    @ResponseBody
    String home() {
    	List<OurCity> cities = cityRepository.findAll();
    	LOG.info("number of cities: " + cities.size());
    	for(OurCity city : cities){
    		LOG.info(city.getName());
    		LOG.info(city.getState());
    	}
        return "Hello World!";
    }
    
    @RequestMapping("/login")
    @Transactional
    public String login(){
    	LoginRecords loginRecords = new LoginRecords();
    	int userId = 1;
    	loginRecords.setUserId(userId);
    	LoginRecords existedLoginRecords = loginRecordsRepository.findOne(userId);
    	int existedLogTimes = existedLoginRecords==null ? 0 :existedLoginRecords.getLogTimes();
    	loginRecords.setLogTimes(existedLogTimes + 1);
    	loginRecordsRepository.save(loginRecords);
    	LOG.info("User: " + loginRecordsRepository.findOne(userId).getUserId() 
    				+ " loing times: " + loginRecordsRepository.findOne(userId).getLogTimes());
    	return "User Login Successfully!";
    }

}